package com.bwda.dsrs.systemservice.service.impl;

import com.bwda.dsrs.systemservice.domain.Constants;
import com.bwda.dsrs.systemservice.domain.condition.role.RoleCondition;
import com.bwda.dsrs.systemservice.domain.condition.userrole.UserRoleCondition;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import com.bwda.dsrs.systemservice.domain.form.user.UserForm;
import com.bwda.dsrs.systemservice.domain.po.org.OrgPo;
import com.bwda.dsrs.systemservice.domain.po.role.RolePo;
import com.bwda.dsrs.systemservice.domain.po.userrole.UserRolePo;
import com.bwda.dsrs.systemservice.mapper.UserRoleMapper;
import com.bwda.dsrs.systemservice.service.OrgService;
import com.bwda.dsrs.systemservice.service.RoleService;
import com.bwda.dsrs.systemservice.service.UserRoleService;
import com.bwda.dsrs.systemservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangjun
 */
@Service
public class UserRoleServiceImpl extends AbstractBaseServiceImpl<UserRolePo, UserRoleCondition, UserRoleMapper> implements UserRoleService {
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private UserService userService;

    @Override
    public List<UserForm> getAuditUserList(String userCode) throws SystemServiceException {

        RoleCondition roleCondition = new RoleCondition();
        roleCondition.setRoleCode(Constants.ORG_ADMIN_ROLE_CODE);
        roleCondition.setDelFlag(Constants.NOT_DELETED);
        List<RolePo> rolePos = roleService.queryList(roleCondition);
        if (CollectionUtils.isEmpty(rolePos)) {
            throw new SystemServiceException("未配置审批角色");
        }
        Integer roleId = rolePos.get(0).getId();
        //查人
        UserRoleCondition userRoleCondition = new UserRoleCondition();
        userRoleCondition.setId(roleId);
        List<UserRolePo> userRolePoList = this.queryList(userRoleCondition);
        StringBuilder userCodes = new StringBuilder();
        userRolePoList.forEach(item -> {
            userCodes.append(item.getUserCode()).append(",");
        });


        //人查出来了，过滤出自己组织及上级组织
        List<OrgPo> orgPoList = orgService.queryOrgByUserCode(userCode);

        //查询这些用户的所属组织
        List<UserForm> userFormList = userService.queryUserByCode(userCodes.toString());

        List<UserForm> auditUsers = new ArrayList<>();

        //遍历筛选，申请人所属组织下的用户
        userFormList.forEach(user -> {
            orgPoList.forEach(org -> {
                if(user.getOrgId().equals(org.getId())){
                    auditUsers.add(user);
                }
            });
        });

        return auditUsers;
    }
}